<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="openDialog">添加角色</el-button>
      <el-table
        :data="roleList"
        style="width: 100%; margin-top: 20px"
        border
        stripe
      >
        <!-- 展开列 -->
        <el-table-column type="expand" class="children-box">
          <template slot-scope="scope">
            <div style="padding: 20px">
              <el-row
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
                :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    key="item1.authName"
                    closable
                    @close="removeRightById(scope.row, item1.id)"
                  >
                    {{ item1.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <el-row
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  >
                    <!--渲染二级权限  -->
                    <el-col :span="5">
                      <el-tag
                        key="item2.authName"
                        closable
                        type="success"
                        @close="removeRightById(scope.row, item2.id)"
                      >
                        {{ item2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="19">
                      <!-- 渲染三级权限 -->

                      <el-col>
                        <el-tag
                          v-for="item3 in item2.children"
                          :key="item3.authName"
                          closable
                          type="warning"
                          @close="removeRightById(scope.row, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="open_roleEdit(scope.row.id)"
              >编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="confirm_del(scope.row.id)"
              >删除
            </el-button>
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editRole" width="50%">
      <!-- 内容主体区域 -->
      <el-form
        label-width="80px"
        :model="form"
        :rules="addRoleRules"
        ref="editRoleformref"
        @close="resetAddForm('editRoleformref')"
      >
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="form.roleId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input autocomplete="off" v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRole = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRole('editRoleformref')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%">
      <!-- 内容主体区域 -->
      <el-form
        label-width="80px"
        :model="addRoleform"
        :rules="addRoleRules"
        ref="addRoleformref"
        @close="resetAddForm('addRoleformref')"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            autocomplete="off"
            v-model="addRoleform.roleDesc"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRole('addRoleformref')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setRight" width="50%">
      <!-- 内容主体区域 -->
      <el-tree
        :data="RightData.data"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="RightData.defaultchecked"
        :props="defaultProps"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRight = false">取 消</el-button>
        <el-button type="primary" @click="setRightData"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      roleList: [],
      dialogVisible: false,
      editRole: false,
      setRight: false,
      // 即将分配权限的对象
      roleId: 0,
      RightData: {
        data: [],
        defaultchecked: []
      },
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      form: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      addRoleform: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ]
      },
      childrenList: []
    }
  },
  created () {
    this.getRoleList()
  },
  computed: {},
  methods: {
    // 获取角色列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 显示添加角色弹框
    openDialog () {
      this.dialogVisible = true
    },
    // 获取所有三级权限
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
    },
    // 显示分配角色弹框
    async showSetRightDialog (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.RightData.data = res.data
      // 重置角色权限列表
      this.RightData.defaultchecked = []
      this.getLeafKeys(role, this.RightData.defaultchecked)
      this.roleId = role.id
      // 显示弹框
      this.setRight = true
    },
    // 为角色赋权
    async setRightData () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.getRoleList()
      this.setRight = false
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 添加用户
    submitAddRole (formName) {
      // 表单预验证
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const { data: res } = await this.$http.post(
            'roles',
            this.addRoleform
          )
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
            this.dialogVisible = false
            return false
          }
          this.$message.success('添加角色成功')
          this.dialogVisible = false
          this.getRoleList()
        } else {
          this.$message.error('添加角色失败')
          this.dialogVisible = false
          return false
        }
      })
    },
    // 编辑角色
    async open_roleEdit (id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.form = res.data
      this.editRole = true
    },
    // 提交编辑角色
    submitEditRole (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'roles/' + this.form.roleId,
            {
              roleName: this.form.roleName,
              roleDesc: this.form.roleDesc
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editRole = false
          this.$message.success('角色信息修改成功')
          this.getRoleList()
        } else {
          this.editRole = false
          return this.$message.error('角色信息修改失败')
        }
      })
    },
    // 删除角色
    confirm_del (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('删除成功')
          this.getRoleList()
        })
        .catch((err) => err)
    },
    // 删除角色权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // 直接重新赋值就行，避免页面的刷新
      role.children = res.data
      return this.$message.success('删除权限成功！')
    }
  }
}
</script>
<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-row {
  line-height: 50px;
  // .el-col {
  //   text-align: center;
  // }
  i {
    cursor: pointer;
  }
}
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
